import {
  Button,
  Col,
  Flex,
  Form,
  Input,
  Modal,
  Row,
  Select,
  Table,
  TreeSelect,
  Upload,
  UploadFile,
  UploadProps,
  message
} from 'antd'
import DraggableDialog from '../DraggableDialog'
import { useEffect, useState } from 'react'

import './index.less'
import EditorExecutor from '@/executor/EditorExecutor'
import { getStationListByUser, stationAndDeviceList } from '@/api/base'
import { handleTree } from '@/util/TreeUtil'
import { FILE_STATUS, FILE_STATUS_OPTIONS, FILE_TYPE, FILE_TYPE_OPTIONS } from '@/constants'
import * as FileApi from '@/api/file'
import dayjs from 'dayjs'
/**
 * 工程管理弹框
 * @Author: zhangshubin
 * @Date: 2023-12-20 09:14:58
 * @Last Modified by: zhangshubin
 * @Last Modified time: 2023-12-20 16:43:46
 *
 */

interface IProjectDialog {
  onClose?: () => void
  //onNew
  onNew?: () => void
  // 点击信息按钮时
  onEdit?: (id: number) => void
}

type FieldType = {
  stationId?: string
  deviceCode?: string
  fileName?: string
  status: number
}

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 }
}

export default function ProjectDialog(props: IProjectDialog) {
  const [form] = Form.useForm()
  // 已保存的数据源
  const [list, setList] = useState([])
  const [current, setCurrent] = useState(1)
  const [pageSize, setPageSize] = useState(1)
  // 总页数
  const [total, setTotal] = useState(0)
  // 电站的树结构
  const [stationTreeData, setStationTreeData] = useState<any[]>([])
  // 设备树
  const [deviceTreeData, setDeviceTreeData] = useState<any[]>([])
  const uploadProps: UploadProps = {
    accept: '.xml,text/xml',
    beforeUpload: (file) => {
      // 读取上传文件
      const reader = new FileReader()
      reader.readAsText(file)
      reader.onload = (e) => {
        const result = e.target?.result
        if (result) {
          const hfile = {
            content: e.target?.result as string,
            meta: {
              name: file.name
            }
          }
          //   props?.onOpen && props?.onOpen(hfile)
          EditorExecutor.open(hfile)
          props?.onClose && props.onClose()
        }
        console.log(e.target?.result)
      }
      return false
    }
  }

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      width: 100,
      key: 'name',
      render: (name: string, row: any) => (
        <Button
          type="link"
          size="small"
          onClick={() => {
            openFile(row)
          }}
        >
          {name}
        </Button>
      )
    },
    {
      title: '归属电站',
      dataIndex: 'stationName',
      width: 120,
      key: 'stationName'
    },
    {
      title: '关联设备',
      width: 100,
      dataIndex: 'deviceName',
      key: 'deviceName'
    },
    {
      title: '类型',
      width: 80,
      dataIndex: 'type',
      key: 'type',
      render: (text: number) => FILE_TYPE_OPTIONS.find((n) => n.value == text)?.label
    },
    // {
    //   title: '说明',
    //   dataIndex: 'description',
    //   key: 'description'
    // },
    {
      title: '最后修改时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (t: number) => {
        return dayjs(t).format('YYYY-MM-DD HH:mm')
      }
    },
    {
      title: '操作',
      dataIndex: 'id',
      key: 'id',
      render: (id: number, row: any) => {
        return (
          <Flex wrap="wrap" gap="small">
            <Button type="link" size="small" onClick={() => props.onEdit && props.onEdit(id)}>
              信息
            </Button>
            <Button type="link" size="small" onClick={() => updateFileStatus(row)}>
              {row.status == FILE_STATUS.DRAFT ? '置为发布' : '置为草稿'}
            </Button>
            <Button type="link" size="small" danger onClick={() => deleteFile(row)}>
              删除
            </Button>
          </Flex>
        )
      }
    }
  ]

  useEffect(() => {
    getStationListByUser().then((data) => {
      console.log(data)
      const stree = handleTree(data)
      setStationTreeData(stree)
      onSearch()
    })
  }, [])

  //查询状态树
  const getDeviceTree = (stationId: number) => {
    stationAndDeviceList(stationId).then((data: any[]) => {
      const list = data.filter(
        (n) =>
          n.productCategoryCode && !['EDGE', 'PCS', 'BMS', 'AM'].includes(n.productCategoryCode)
      )
      const tree = handleTree(list)
      setDeviceTreeData(tree)
    })
  }

  // 查询库里的SVG图
  const onSearch = () => {
    form.validateFields().then((values) => {
      sendPageRequest(values, 1, 10)
    })
  }

  // 发起分页请求
  const sendPageRequest = async (values: any, pageNo: number = 1, pageSize: number = 10) => {
    const req = {
      ...values,
      pageNo,
      pageSize
    }
    const data = await FileApi.queryFileList(req)
    setList(data.list)
    setTotal(data.total)
    setCurrent(pageNo)
    setPageSize(pageSize)
  }

  /**
   * 打开文件
   * @param path
   */
  const openFile = async (meta: HFileMeta) => {
    //@ts-ignore
    const content = await FileApi.requestFile(meta.svgPath)
    if (content) {
      const file = {
        meta,
        content
      }
      EditorExecutor.open(file)
    }
    props.onClose && props.onClose()
  }

  // 删除文件
  const deleteFile = async (row: any) => {
    Modal.confirm({
      content: `确定删除文件-${row.name}？`,
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        doDelete(row.id)
      },
      onCancel() {}
    })
  }

  //更新文件的发布状态
  const updateFileStatus = async (row: any) => {
    const msg =
      row.status == FILE_STATUS.DRAFT ? `确认发布${row.name}么？` : `确认取消发布${row.name}么？`

    Modal.confirm({
      content: msg,
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        doUpdateFileStatus(row)
      },
      onCancel() {}
    })
  }
  // 执行更新操作
  const doUpdateFileStatus = async (row: any) => {
    const status = row.status == FILE_STATUS.DRAFT ? FILE_STATUS.PUBLISHED : FILE_STATUS.DRAFT

    const result = await FileApi.updateGraphFileStatus(row.id, status)
    const msg = status == FILE_STATUS.PUBLISHED ? '发布' : '取消发布'
    if (result) {
      message.success(`${msg}成功！`)
      onSearch()
    } else {
      message.error(`${msg}失败！`)
    }
  }

  // 执行删除
  const doDelete = async (id: number) => {
    const result = await FileApi.deleteGraphFile(id)
    if (result) {
      message.success('删除成功')
      onSearch()
    } else {
      message.error('删除失败！')
    }
  }

  return (
    <DraggableDialog
      title="工程管理"
      open={true}
      onCancel={props.onClose}
      width={800}
      footer={[
        <Button
          type="primary"
          key="close"
          size="small"
          className="font-size-12px!"
          onClick={(e) => props.onClose && props.onClose()}
        >
          关闭
        </Button>
      ]}
    >
      <Form name="searchForm" form={form} layout="inline" {...layout} onFinish={onSearch}>
        <Row className="w-100%">
          <Col span={8}>
            {' '}
            <Form.Item<FieldType>
              label="电站"
              name="stationId"
              rules={[{ required: false }]}
              className="font-size-12px!"
            >
              <TreeSelect
                showSearch
                allowClear
                style={{ width: '100%' }}
                className="w-100% h-26px font-size-12px"
                popupClassName="font-size-12px!"
                dropdownStyle={{ minWidth: 200, fontSize: '12px' }}
                placeholder="请选择电站"
                treeDefaultExpandAll
                fieldNames={{
                  label: 'stationName',
                  value: 'id'
                }}
                treeData={stationTreeData}
                onChange={(v) => {
                  form.setFieldValue('deviceCode', '')
                  getDeviceTree(v)
                }}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item<FieldType> label="设备" name="deviceCode" rules={[{ required: false }]}>
              <TreeSelect
                showSearch
                allowClear
                style={{ width: '100%' }}
                className="w-100% h-26px font-size-12px"
                popupClassName="font-size-12px!"
                dropdownStyle={{ minWidth: 200, overflow: 'auto', fontSize: '12px' }}
                placeholder="请选择设备"
                allowClear
                treeDefaultExpandAll
                fieldNames={{
                  label: 'deviceName',
                  value: 'deviceCode'
                }}
                treeData={deviceTreeData}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item<FieldType> label="文件" name="fileName" rules={[{ required: false }]}>
              <Input className="h-26px" allowClear />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item<FieldType> label="状态" name="status" rules={[{ required: false }]}>
              <Select className="h-26px" options={FILE_STATUS_OPTIONS} allowClear />
            </Form.Item>
          </Col>
          <Col span={8}></Col>
          <Col span={8} className="flex flex-justify-end flex-items-center">
            <Button type="primary" size="small" className="font-size-12px! " htmlType="submit">
              查询
            </Button>
            <Button
              size="small"
              className="font-size-12px! ml-10px"
              onClick={() => {
                props.onNew && props.onNew()
              }}
            >
              新建
            </Button>
            <Upload {...uploadProps}>
              <Button size="small" className="font-size-12px! ml-10px">
                本地文件
              </Button>
            </Upload>
          </Col>
        </Row>
      </Form>
      <Table
        className="mt-10px"
        columns={columns}
        rowKey={(row) => row.id}
        dataSource={list}
        size="small"
        bordered
        pagination={{
          current,
          pageSize,
          total,
          onChange: (page, pageSize) => {}
        }}
      ></Table>
    </DraggableDialog>
  )
}
